#include "InetAddress.h"
#include <strings.h>
#include <string.h>
// 加explicit是一个好习惯
// 参数的声明和定义都只能出现一次，缺省参数也不能带！
InetAddress::InetAddress(uint16_t port, std::string ip)
{
    bzero(&addr_, sizeof addr_);
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port);
    addr_.sin_addr.s_addr = inet_addr(ip.c_str()); // 转化成网络字节序，
}
std::string InetAddress::toIp() const
{
    // addr_ 里面读ip地址,但是已经是网络字节序了！
    char buf[64] = {0};
    ::inet_ntop(AF_INET, &addr_.sin_addr, buf,sizeof(buf));
    return buf;
}
std::string InetAddress::toIpPort() const
{
    // ip:port
    char buf[64] = {0};
    // sin_addr 默认是 uint32_t
    ::inet_ntop(AF_INET, &addr_.sin_addr, buf,sizeof(buf));
    size_t end = strlen(buf);
    uint16_t port = ntohs(addr_.sin_port);
    sprintf(buf + end, ":%u", port); // %u 就是无符号的格式

    return buf;
}
uint16_t InetAddress::toPort() const
{
    return ntohs(addr_.sin_port);
}


// #include<iostream>
// using namespace std;
// int main()
// {
//     InetAddress addr(8080);
//     std::cout << addr.toIpPort() << endl;
//     return 0;
// }